package cn.lifeaid.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.lifeaid.db.SysRole;
import cn.lifeaid.db.SysRoleExample;

@Service
public class SysRoleServiceImpl implements SysRoleService {

	@Autowired
	SqlSession sqlSession;
	@Autowired
	private SysResourceService resourceService;

	@Override
	public void createRole(SysRole role) {
		sqlSession.insert("cn.lifeaid.db.SysRoleMapper.insert", role);
	}

	@Override
	public void updateRole(SysRole role) {
		sqlSession.update("cn.lifeaid.db.SysRoleMapper.updateByPrimaryKey",
				role);
	}

	@Override
	public void deleteRole(Long roleId) {
		sqlSession.delete("cn.lifeaid.db.SysRoleMapper.deleteByPrimaryKey",
				roleId);
	}

	@Override
	public SysRole findOne(Long roleId) {
		return sqlSession.selectOne(
				"cn.lifeaid.db.SysRoleMapper.selectByPrimaryKey", roleId);
	}

	@Override
	public List<SysRole> findAll() {
		return findByExample(new SysRoleExample());
	}

	@Override
	public Set<String> findRoles(Long... roleIds) {
		Set<String> roles = new HashSet<String>();
		for (Long roleId : roleIds) {
			SysRole role = findOne(roleId);
			if (role != null) {
				roles.add(role.getRole());
			}
		}
		return roles;
	}

	@Override
	public Set<String> findPermissions(Long[] roleIds) {
		Set<Long> resourceIds = new HashSet<Long>();
		for (Long roleId : roleIds) {
			SysRole role = findOne(roleId);
			if (role != null) {
				resourceIds.addAll(getResourceIds(role));
			}
		}
		return resourceService.findPermissions(resourceIds);
	}

	@Override
	public List<SysRole> findByExample(SysRoleExample example) {
		return sqlSession.selectList(
				"cn.lifeaid.db.SysRoleMapper.selectByExample", example);
	}

	@Override
	public List<Long> getResourceIds(SysRole role) {
		List<Long> resourceIds = new ArrayList<Long>();
		if (null != role) {
			String[] resourceIdStrs = role.getResourceIds().split(",");
			for (String resourceIdStr : resourceIdStrs) {
				if (StringUtils.isEmpty(resourceIdStr)) {
					continue;
				}
				resourceIds.add(Long.valueOf(resourceIdStr));
			}
		}
		return resourceIds;
	}

}
